package top.techqi.view.recyclerview

import androidx.recyclerview.widget.RecyclerView

/**
 * 表格布局管理器。整体不可滚动，行列数已固定，每项宽高相同。
 */
class TableLayoutManager(val rowCount: Int, val colCount: Int) : RecyclerView.LayoutManager() {
    override fun canScrollHorizontally(): Boolean = false
    override fun canScrollVertically(): Boolean = false

    override fun generateDefaultLayoutParams(): RecyclerView.LayoutParams {
        return RecyclerView.LayoutParams(
            RecyclerView.LayoutParams.MATCH_PARENT,
            RecyclerView.LayoutParams.MATCH_PARENT
        )
    }

    override fun onLayoutChildren(recycler: RecyclerView.Recycler, state: RecyclerView.State) {
        if (itemCount == 0) {
            removeAndRecycleAllViews(recycler)
            return
        }

        detachAndScrapAttachedViews(recycler)

        val itemHeight = height / rowCount
        val itemWidth = width / colCount

        for (index in 0 until itemCount) {
            val child = recycler.getViewForPosition(index)
            addView(child)

            measureChildWithMargins(child, itemWidth * (colCount - 1), itemHeight * (rowCount - 1))
            val width = getDecoratedMeasuredWidth(child)
            val height = getDecoratedMeasuredHeight(child)
            val row = index / colCount
            val col = index % colCount
            layoutDecorated(
                child,
                col * itemWidth, row * itemHeight,
                col * itemWidth + width, row * itemHeight + height
            )
        }
    }
}